package com.cy.exception;

import com.cy.pojo.JsonResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResult myExceptionHandler(MethodArgumentNotValidException exception){
        exception.printStackTrace();
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg=new StringBuilder();

        if(result.hasErrors()){
        List<FieldError> fieldErrors= result.getFieldErrors();
            for (FieldError error:fieldErrors) {
                System.out.println("field" + error.getField() + ", msg:" + error.getDefaultMessage());
                errorMsg.append(error.getDefaultMessage()).append("!");
            }
        }
        exception.printStackTrace();
        return new JsonResult(-1,errorMsg.toString());
    }
}
